package priv.zgh.forum.utils;

import com.google.code.kaptcha.impl.DefaultKaptcha;
import priv.zgh.forum.auth.entity.ZhengGu;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;

public class CaptchaUtils {
    /**
     * 生成验证码图片
     * @param request 设置session
     * @param response 转成图片
     * @param captchaProducer 生成图片方法类
     * @param validateSessionKey session名称
     * @throws Exception
     */
    public static void validateCode(HttpServletRequest request, HttpServletResponse response, DefaultKaptcha captchaProducer, String validateSessionKey, ZhengGu code) throws Exception{
        // 设置http请求头
        response.setDateHeader("Expires", 0);
        response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
        response.addHeader("Cache-Control", "post-check=0, pre-check=0");
        response.setHeader("Pragma", "no-cache");
        // 设置返回类型
        response.setContentType("image/jpeg");
        // 创建图像文本
        String capText = captchaProducer.createText();
        // 将内容存储到Session中
        request.getSession().setAttribute(validateSessionKey, capText);
        code.setTemp(capText);
        BufferedImage bi = captchaProducer.createImage(capText);
        ServletOutputStream out = response.getOutputStream();
        // 写出
        ImageIO.write(bi, "jpg", out);
        try {
            out.flush();
        } finally {
            out.close();
        }
    }
}
